<template>
    <div :style="{ height: scrollHeight + 'px' }" class="width100">
      <el-form
        ref="departmentDetailForm"
        :model="content"
        label-position="top"
        label-width="180px"
        size="mini"
        class="form-inline formMain  "
        :rules="rules"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item
              :label="$t('dept_name')"
               
              prop="name"
            >
              <el-input type="text" v-model="content.name" @input="inputChange"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="4">
            <el-form-item :label="$t('orderByNo')"  >
              <el-input
                type="number"
                v-model="content.orderByNo"
                @blur="onOrderByNoBlur"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item :label="$t('superior_dept')"  >
              <el-input
                type="text"
                :readonly="true"
                :placeholder="$t('please_select_dept')"
                :value="content.superior ? content.superior.name : ''"
              >
              <template slot="append">
                <el-button @click="onSelectDept">
                  {{ $t('select_dept') }}
              </el-button>
              </template>
            </el-input>
              
            </el-form-item>
          </el-col>
          <!-- <el-col :span="2">
            <el-form-item>
              <el-button @click="onSelectDept" class="marginTop29">
                {{ $t('select_dept') }}
              </el-button>
            </el-form-item>
          </el-col> -->
          <el-col :span="6" :offset="4">
            <el-form-item :label="$t('code')"  >
              <el-input type="text" v-model="content.code"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item
              :label="$t('valid')"
              class=" switchItem"
            >
              <el-switch
                v-model="content.valid"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <extend_flex 
          :contextPath="contextPath"
          :fieldextends="fieldextends"
          :content="content"
        />
        <!-- 用户列表 -->
        <p class="smallHeader">{{ $t('owned_user') }}</p>
        <el-table
          :data="content.subUser ? content.subUser.datas : []"
          stripe
          ref="departmentDetailUser"
          header-cell-class-name="tableHeaderbg"
        >
          <el-table-column prop="name" :label="$t('name')"></el-table-column>
          <el-table-column
            prop="loginno"
            :label="$t('loginno')"
          ></el-table-column>
          <el-table-column prop="email" :label="$t('email')"></el-table-column>
          <el-table-column
            prop="telephone"
            :label="$t('tel')"
          ></el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange2"
          @current-change="searchTableData2"
          :current-page.sync="searchdata2.currpage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="searchdata2.pagelines"
          :page-count="4"
          layout="prev, pager, next, total, sizes"
          background
          :total="content.subUser ? content.subUser.rowCount : 0"
        ></el-pagination>
      </el-form>
    </div>
</template>

<script>
import extend_flex from "@/components/extendFlex.vue";
import { scrollHeight,checkHasId } from '@/utils'
export default {
  name: 'department_detail',
  data() {
    return {
      content:{},
      fieldextends:[],
      contextPath:this.$api.getContextPath(),
      scrollHeight: scrollHeight,
      searchdata2: {
        currpage: 1,
        pagelines: 5,
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
        ],
      },
    }
  },
  components: {
    extend_flex,
  },
  created() {
    this.content=this.detail
    // this.$nextTick(()=>{
    //   this.$refs['departmentDetailForm'].resetFields();
    // })
    let that=this
    let dataJson={ 
      currpage:1,
      pagelines:999,
      data:{
        type:"",
        fortable:"tableDept",
        domainid: this.$route.query.domainid,
        belong:"All"
      }
    }
    debugger
    // this.$api.getFieldExtends(
    //  dataJson,
    //   {
    //     onSucess: resp => {
    //       resp.data.data.datas.forEach( elm => {
    //         if(elm.type == "radio" || elm.type == "select" || elm.type == "checkbox"){
    //           let option = elm.options.split(";");
    //           let arr = [];
    //           if(elm.type == "radio" || elm.type == "select"){
    //             for(let i=0;i<option.length;i++){
    //               let obj = {}
    //               obj.label = option[i];
    //               obj.value = option[i];
    //               arr.push(obj);
    //             }
    //             elm.options = arr;
    //           }else if(elm.type == "checkbox"){
    //             elm.checkboxList = this.content[elm.name] ? this.content[elm.name].split(";") : [];
    //             elm.options = option;
    //           }
    //         }else if(elm.type == "address") {
    //           if(typeof(this.content[elm.name])=='string'){
    //           this.content[elm.name+'_registerAddress'] = this.content[elm.name].split(',')[3];
    //           let arr = [];
    //           arr.push(this.content[elm.name].split(',')[0],this.content[elm.name].split(',')[1],this.content[elm.name].split(',')[2])
    //           this.content[elm.name] = arr;
    //           }
    //         }
    //         that.fieldextends.push(elm)
    //         // 遍历查找看是否有对应的值
    //         if(that.fieldextends[that.fieldextends.length]){
    //           that.content[elm.name] = checkHasId(that.fieldextends[that.fieldextends.length].options, that.content[elm.name], 'label')
    //         }
    //       })
    //     }
    //   }
    // );
  },
  methods: {
    inputChange() {//文本框可能因为层级太深，使输入框失效，this.$forceUpdate()强制刷新。
      this.$forceUpdate();   
    },
    back(){
      this.$emit('back')
    },
    //保存
    onSaveBtnClick() {
      this.$refs['departmentDetailForm'].validate((valid)=>{
        if(valid){
          if (parseInt(this.content.orderByNo) < 0) {
        this.$message({
          showClose: true,
          message: this.$t('msg_orderno_negative'),
          type: 'error',
        })
        return false
      }else if(this.content.orderByNo > 2147483647){
        this.$message({
          showClose: true,
          message: '请输入0-2147483647的数字',
          type: 'error',
        })
        return false
      }
      // 判断当前项是否为必填项
      let checkArr = []
      let checkTip = ''
      let have = true
      if (this.fieldextends.length > 0) {
        this.fieldextends.map((item) => {
          if (item.isNotNull) {
            checkArr.push(item)
          }
          if(item.type == "address"){
            this.content[item.name]
            if(this.content[item.name+'_registerAddress']){
              if(typeof(this.content[item.name]) == "string"){
                this.content[item.name] = this.content[item.name] + "," + this.content[item.name+'_registerAddress'];
              }else{
                this.content[item.name].push(this.content[item.name+'_registerAddress'])
              }
            }
            if(this.content[item.name]){
              this.content[item.name] = this.content[item.name].toString();
            }
          }
        })
        if (checkArr.length > 0) {
          checkArr.some((ele) => {
            if (!this.content[ele.name]) {
              have = false
              checkTip += ele.label + ','
            }else if(ele.type=='address'){
             if(typeof(this.content[ele.name])=='object'){
                if(!this.content[ele.name][0]){have=false;checkTip += ele.label + ',';}
             }else if(typeof(this.content[ele.name]=='string')){
               if(!this.content[ele.name].replace(/\,/g,'')) {have=false;checkTip += ele.label + ',';}
             }
           }
          })
        }
        if (!have) {
          this.$message.error(
            checkTip.substring(0, checkTip.lastIndexOf(',')) + '字段为必填项'
          )
          return false
        }
      }
      // 将所有的null替换为''
      for (let i in this.content) {
        if (this.content[i] == null) this.content[i] = ''
      }

      if (this.content.superior) {
        for (let j in this.content.superior) {
          if (this.content.superior[j] == null) this.content.superior[j] = ''
        }
      }

      let content = JSON.parse(JSON.stringify(this.content))
      if (content && content.id) {
        //更新
        if (content.superior) {
          content.superiorid = content.superior.id
        }
        this.$api.updateDepartment(
          {
            departmentid: content.id,
            data: content,
          },
          {
            onSucess: (resp) => {
              if (resp.data.errcode == 0) {
                this.$message({
                  showClose: true,
                  message: this.$t('msg_save_success'),
                  type: 'success',
                })
                this.timer = new Date().getTime()
                this.back();
                this.$$parent.searchTableData();
              } else {
                this.$message({
                  showClose: true,
                  message: resp.data.errmsg,
                  type: 'error',
                })
              }
            },
          }
        )
      } else {
        //新建
        if (content.superior) {
          content.superiorid = content.superior.id
        }
        this.$api.createDepartment(
          { data: content },
          {
            onSucess: (resp) => {
              if (resp.data.errcode == 0) {
                this.$message({
                  showClose: true,
                  message: this.$t('msg_save_success'),
                  type: 'success',
                })
                this.timer = new Date().getTime()
                this.back();
              } else {
                // resp.data.errmsg
                this.$message({
                  showClose: true,
                  message: resp.data.errmsg,
                  type: 'error',
                })
              }
            },
          }
        )
      }
        }else{
          console.log('error submit')
          return false;
        }
      })
    },
    handleSizeChange2(size) {
      this.searchdata2.pagelines = size
      this.searchTableData2()
    },

    searchTableData2() {
      this.$api.getDepartmentUsers(this.content.id, this.searchdata2, {
        onSucess: (resp) => {
          this.content.subUser = resp.data.data
          this.$forceUpdate()
        },
      })
    },
    onOrderByNoBlur() {
      this.content.orderByNo = parseInt(this.content.orderByNo)
    },
    onSelectDept() {
      this.$emit('onSelectDept')
    },
  },
  props: {
    isNew: {
      type: Boolean,
      default: true
    },
    detail: Object
  }
}
</script>
<style lang='scss' scoped>
</style>